import Request from './request.js'

// need to change baseUrl
//点击运行 process.env.NODE_ENV ==='development'为开发环境  http://192.168.0.132
const baseUrl = process.env.NODE_ENV === 'development' ? "https://pt.huntarray.com/prod-api" : "https://pt.huntarray.com/prod-api"

const config = {
	baseUrl: baseUrl
}

const reqInterceptor = async (options) => {
	//TODO do your request interceptor
	   uni.showLoading({
			title: '加载中'
		});
	   let token= uni.getStorageSync("token")
	   if(!token&&options.authType!="None"){ 
		   uni.showToast({
		   	title:"请注册登陆!"
		   })
		   uni.navigateTo({
		   	url: '/pages/mine/auth/auth',
		   });
		   return;
	   }
	   
	   if(token&&options.authType!="None"){
			options.header["Authorization"]=token;
	   }else{
		   // options.header.remove
	   }
	  
	  
	   options.header['Content-Type']= 'application/json'
	   _requestLog(options, "成功通过")
		// return false will abort the request
	   return options
}

const resInterceptor = (response, conf={}) => {
	// TODO do your response
	const statusCode = response.statusCode
	
	
	uni.hideLoading();
	// response interceptor
	if (statusCode >= 200 && statusCode < 300) { //成功
	_responseLog(response, conf, "response 200-299")
		return response
	} else if (statusCode === 500) {
		_responseLog(response, conf, "response 500")
		// return false will reject the response
		return false
	} else {
		_responseLog(response, conf, "response 300-499")
		return false
	}
}

const req = new Request(config, reqInterceptor, resInterceptor)

// request log
function _requestLog(req, describe=null) {
	if (process.env.NODE_ENV === 'development') {
		console.log("地址：" + req.url)
		if (describe) {
			console.log("描述：" + describe)
		}
		console.log("详细：" + JSON.stringify(req))
	}
	//TODO into log server
}

// response log
function _responseLog(res, conf={}, describe=null) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		console.log("地址: " + conf.url)
		if (describe) {
			console.log("描述：" + describe)
		}
		console.log("结果: " + JSON.stringify(res))
	}
	
	
	
	//TODO into log server
	if (_statusCode === 500) {
		createAppFeed({
			title: '500: 服务器错误',
			detail: conf.url,
			version: 'v1'
		})
	}
}

export default req
